//
//  NWTabBar.swift
//  Weibo
//
//  Created by Northwan on 16/1/20.
//  Copyright © 2016年 Northwan. All rights reserved.
//

import UIKit

//如果声明代理时想要使用weak修饰，就必须要让代理继承于基协议 NSObjectProtocol
protocol NWTabBarDelegate : NSObjectProtocol{
    func composeButtonClick()
}

class NWTabBar: UITabBar {
    
    /// 1.声明代理执行+号点击回调
    weak var mDelegate:NWTabBarDelegate?
    
    /// 2.定义点击+号回调的闭包
    var composeButtonClosure:(()->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    //如果是从xib/sb中创建会调用这个方法，为什么必须需要重写，是因为制定的规则别人不一定会遵守
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
         setupUI()
    }
    
    func setupUI(){
        //设置tabbar背景图片（同时能够解决导航栏最右面阴影的bug）
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
     
        //给子控件设置center的时候不要使用父控件的宽度参与计算
        composeButton.center = CGPoint(x:frame.width*0.5, y: frame.height*0.5)
        
        let childW = frame.width/5;
        var index = 0
        for childView in subviews{
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!){
                let x = CGFloat(index) * childW
                childView.frame = CGRect(x:x , y: 0, width: childW, height: frame.height)
//                printLog(childView)
                index++
                //如果是第二个按钮，继续++一次调整位置
                if index == 2 {
                    index++
                }
            }
        }
    }
    
    // MARK: - 点击事件
    @objc private func composeButtonClick(){
        composeButtonClosure?()
    }
    
    // MARK: - 懒加载控件
    
    /// 撰写按钮
    lazy var composeButton:UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        //设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        
        return button
    }()
    
    deinit{
        printLog("deinit------------")
    }

}
